

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.connector.Request;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class loginService
 */
@WebServlet("/loginService")
public class loginService extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private String userName;
    private String password;
    private int hostFamilyID;
    private int guestProfileID;
    //private Session session;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public loginService() {
        super();
        hostFamilyID=0;
		//session = HibernateUtil.getSessionFactory().getCurrentSession();
		//session.beginTransaction();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		userName = request.getParameter("userName");
		password = request.getParameter("pwd");
		List result1 = getUserByAccount(1, userName, password);
		if (result1==null || result1.isEmpty()){
			List result2 = getUserByAccount(2, userName, password);
			if(result2==null || result2.isEmpty()){
				out.println("<html><head><title>host Manager</title></head><body>");
	    		out.println("<a>sql 1403: no user exits</a>");
	    		out.println("</body></html>");
			}
			else
			{
				guestUser guestUserObj = (guestUser) result2.get(0);
				guestProfileID = getGuestProfileIDByGuestUserID(guestUserObj.getGuestUserId());
	    		HttpSession guestSession = request.getSession(true);
	    		guestSession.setAttribute("guestUserID", guestUserObj.getGuestUserId());
	    		guestSession.setAttribute("UserType", guestUserObj.getUserType());
	    		guestSession.setAttribute("guestProfileID", guestProfileID);
	    		guestSession.setAttribute("isLogged", "Yes");
	    		//request.getRequestDispatcher("Edit-Guest-Profile.html").forward(request, response);
		        //request.getRequestDispatcher("/guests/").forward(request, response);
	    		response.sendRedirect("/HBSPROJECT/guests/");
			}
		}
		else{
			hostUser hostUserObj = new hostUser();
			hostUserObj = (hostUser) result1.get(0);
			hostFamilyID = getFamilyIDByHostUserID(hostUserObj.getHostUserId());
    		HttpSession hostsession = request.getSession(true);
    		hostsession.setAttribute("hostUserID", hostUserObj.getHostUserId());
    		hostsession.setAttribute("UserType", hostUserObj.getUserType());
    		hostsession.setAttribute("hostFamilyID", hostFamilyID);
    		hostsession.setAttribute("isLogged", "Yes");
	        //request.getRequestDispatcher("Edit-Host-Family.html").forward(request, response);
    		//request.getRequestDispatcher("ChangePass.html").forward(request, response);
	        response.sendRedirect("/HBSPROJECT/hosts/");
		}
	}
	protected List getUserByAccount(int table,String x_userName,String x_password)
	{

		List temp = null;
		try{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        if(table==1)
        {
        	String sqlString = "select * from hostusers where account = '" + x_userName + "' "
                               + "and password = '" + x_password + "'";
			Query queryResult = session.createSQLQuery(sqlString).addEntity(hostUser.class);;
	        temp = queryResult.list();
        }
        else
        {
        	String sqlString = "select * from guestusers where account = '" + x_userName + "' "
                               + "and password = '" + x_password + "'";
        	Query queryResult2 = session.createSQLQuery(sqlString).addEntity(guestUser.class);;
	        temp = queryResult2.list();
        }
        session.getTransaction().commit();
		} catch(Exception ex){
			HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
		}
        return temp;
	}
	protected int getFamilyIDByHostUserID(int hostUserID)
	{
		List temp = null;
		hostFamily hostFamilyObj = new hostFamily(0);
		try{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        String sqlString = "select * from hostfamilies where hostuserID = " + hostUserID;
		Query queryResult = session.createSQLQuery(sqlString).addEntity(hostFamily.class);;
	    temp = queryResult.list();
	    hostFamilyObj = (hostFamily) temp.get(0);
        session.getTransaction().commit();
		} catch(Exception ex){
			HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
		}
        return hostFamilyObj.getHostFamilyID();
	}
	protected int getGuestProfileIDByGuestUserID(int guestUserID)
	{
		List temp = null;
		guestProfile guestProfileObj = new guestProfile(0);
		try{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        String sqlString = "select * from guestsprofiles where guestuserID = " + guestUserID;
		Query queryResult = session.createSQLQuery(sqlString).addEntity(guestProfile.class);;
	    temp = queryResult.list();
	    guestProfileObj = (guestProfile) temp.get(0);
        session.getTransaction().commit();
		} catch(Exception ex){
			HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
		}
        return guestProfileObj.getGuestProfileID();
	}
}
